<?php

namespace App\Models;

class ForumTopic extends Model
{
    protected $fillable = ['title', 'body', 'category_id',  'excerpt', 'slug',];


    protected $hidden=[''];

    /**
     * 与模型关联的数据表
     *
     * @var string
     */
    protected $table = 'forum_topics';

    //表关联
    public function user()
    {
        return $this->belongsTo(User::class,"user_id","id")->withDefault([
            'name' => '该用户已被删除',
        ]);
    }

    public function forumCategory()
    {
        return $this->belongsTo(ForumCategory::class,"category_id","id")->withDefault([
            'name' => '该分类已被删除',
        ]);
    }
    public function lastReplyUser()
    {
        return $this->belongsTo(User::class,"last_reply_user_id")->withDefault([
            'name' => '该用户已被删除',
        ]);
    }

    //帖子回复表关联
    public function replies()
    {
        return $this->hasMany(Reply::class,'forumTopic_id','id');
    }




    //帖子urlSEO优化
    public function link($params = [])
    {
        return route('topics.show', array_merge([$this->id, $this->slug], $params));
    }




    //帖子排序方式
    public function scopeWithOrder($query, $order)
    {
        // 不同的排序，使用不同的数据读取逻辑
        switch ($order) {

            case 'replyCount':
                //创建时间
                $query = $this->replyCount();
                break;
            case 'recent':
                //创建时间
                $query = $this->recent();
                break;

            default:
                //最好回复
                $query = $this->recentReplied();
                break;
        }
        // 预加载防止 N+1 问题
        return $query->with('user', 'forumCategory');
    }
    public function scopeReplyCount($query)
    {
        return $query->orderBy('reply_count', 'asc');
    }
    public function scopeRecentReplied($query)
    {
        // 当话题有新回复时，我们将编写逻辑来更新话题模型的 reply_count 属性，
        // 此时会自动触发框架对数据模型 updated_at 时间戳的更新
        return $query->orderBy('updated_at', 'desc');
    }

    public function scopeRecent($query)
    {
        // 按照创建时间排序
        return $query->orderBy('created_at', 'desc');
    }


}